﻿const http = require('http');
const mongoose = require('mongoose');
const { MongoClient, ServerApiVersion } = require('mongodb');

const app = require('./app');

const PORT = process.env.PORT || 8000;

const { loadPlanetsData } = require('./models/planets.model');


const MONGO_URL = 'mongodb+srv://haochen214_db_user:hao@chen214@castle0.2ho5jpg.mongodb.net/nasa?retryWrites=true&w=majority&appName=Castle0';
//hao@chen214
const uri = "mongodb+srv://haochen214_db_user:hao@chen214@castle0.2ho5jpg.mongodb.net/?retryWrites=true&w=majority&appName=Castle0";

// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
    serverApi: {
        version: ServerApiVersion.v1,
        strict: true,
        deprecationErrors: true,
    }
});

const server = http.createServer(app);

mongoose.connection.once('open', () => {
    console.log('MongoDB Connected ready');
});

mongoose.connection.on('error',(err) =>{
    console.error(err);
});

async function startServer() {
    // await mongoose.connect(MONGO_URL,{
    //     useNewUrlParser: true,
    //     useFindAndModify: false,
    //     useCreateIndex: true,
    //     useUnifiedTopology: true,
    // });

    try {
        // Connect the client to the server	(optional starting in v4.7)
        await client.connect();
        // Send a ping to confirm a successful connection
        await client.db("admin").command({ ping: 1 });
        console.log("Pinged your deployment. You successfully connected to MongoDB!");
    } finally {
        // Ensures that the client will close when you finish/error
        await client.close();
    }

    //await loadPlanetsData();

    server.listen(PORT,() =>{
        console.log('listening on port '+PORT);
    });
}

startServer().catch(console.dir);













